import { createStore, useStore as baseUseStore, Store } from 'vuex'
import { InjectionKey } from 'vue'
import { setItem, getItem, removeItem } from '@/utils/storage'

const state = {
  dataObj: getItem('dataObj') || {}, // 数据
}

export type State = typeof state

// 定义 injection key
export const key: InjectionKey<Store<State>> = Symbol()

// 创建一个新的 store 实例
export const store = createStore<State>({
  state,
  mutations: {
    // 保存用户信息
    setData(state: any, payload: any) {
      const { name, data } = payload
      state.dataObj[name] = data
      setItem('dataObj', state.dataObj)
    },
    deleteUser(state: any, payload: any) {
      state.user = payload
      removeItem('dataObj')
    },
  },
})

// 定义自己的 `useStore` 组合式函数
export function useStore() {
  return baseUseStore(key)
}
